<template>
  <!-- 登录容器 -->
  <div class="login-container">
    <!-- 顶部logo -->
    <div class="logo">
      <img src="@/assets/bigLogo.png"/>
    </div>

    <!-- 登录表单 -->
    <div class="login-form">
      <!-- 登录方式切换 -->
      <div class="login-tabs">
        <!-- 密码登录标签 -->
        <div :class="['tab-item', activeTab === 'password' ? 'active' : '']" @click="switchTab('password')">
          密码登录
        </div>
        <!-- 短信登录标签 -->
        <div :class="['tab-item', activeTab === 'sms' ? 'active' : '']" @click="switchTab('sms')">
          验证码登录
        </div>
      </div>

      <!-- 密码登录表单 -->
      <div v-if="activeTab === 'password'" class="form-content">
        <!-- 手机号输入框 -->
        <div class="form-item">
          <input
              v-model="phone"
              type="tel"
              placeholder="请输入手机号"
              maxlength="11"
              @input="validatePhone"
          />
        </div>

        <!-- 密码输入框 -->
        <div class="form-item">
          <input
              v-model="password"
              :type="showPassword ? 'text' : 'password'"
              placeholder="请输入密码"
          />
        </div>

        <!-- 登录按钮 -->
        <button
            class="login-btn"
            :disabled="!canLogin"
            @click="triggerLoginWithCaptcha"
        >
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </div>

      <!-- 短信登录表单 -->
      <div v-else class="form-content">
        <!-- 手机号输入框 -->
        <div class="form-item">
          <input
              v-model="phone"
              type="tel"
              placeholder="请输入手机号"
              maxlength="11"
              @input="validatePhone"
          />
        </div>

        <!-- 验证码输入框和获取按钮 -->
        <div class="form-item">
          <!-- 短信验证码输入框，添加:disabled控制是否可输入 -->
          <input
              v-model="smsCode"
              type="text"
              placeholder="请输入验证码"
              maxlength="6"
              :disabled="!smsVerified"
          >
          <!-- 获取验证码按钮 -->
          <button
              class="sms-btn"
              :disabled="!canGetSmsCode"
              @click="triggerSmsCaptcha"
          >
            {{ smsCountdown > 0 ? `${smsCountdown}s后重试` : '获取验证码' }}
          </button>
        </div>

        <!-- 登录按钮 -->
        <button
            class="login-btn"
            :disabled="!canSmsLogin"
            @click="handleSmsLogin"
        >
          登录
        </button>
      </div>

      <!-- 注册链接 -->
      <div class="register-link">
        还没有账号？<span @click="showRegisterDialog = true">立即注册</span>
      </div>
    </div>

    <!-- 注册弹窗 -->
    <RegisterDialog v-if="showRegisterDialog" @close="showRegisterDialog = false"/>

    <!-- 密码登录验证码组件（动态渲染） -->
    <SlideCaptcha
        v-if="showLoginCaptcha"
        ref="loginCaptcha"
        :app-id="captchaAppId"
        @success="onLoginCaptchaSuccess"
        @fail="onCaptchaFail"
    />

    <!-- 短信验证码组件（动态渲染） -->
    <SlideCaptcha
        v-if="showSmsCaptcha"
        ref="smsCaptcha"
        :app-id="captchaAppId"
        @success="onSmsCaptchaSuccess"
        @fail="onCaptchaFail"
    />

    <Navigation/>
  </div>
</template>

<script setup lang="ts">
// 导入Vue相关功能
import {computed, getCurrentInstance, nextTick, ref} from "vue";
// 导入验证码组件
import SlideCaptcha from "@/components/LoginComponents/SlideCaptcha.vue";
// 导入注册弹窗组件
import RegisterDialog from "@/components/LoginComponents/RegisterDialog.vue";
// 导入Toast提示组件
import {showToast} from "vant";
import { useRouter } from 'vue-router'
import Navigation from "@/components/homepageComponents/Navigation.vue";

const router = useRouter()

const global = getCurrentInstance().appContext.config.globalProperties;

// 验证码应用ID
const captchaAppId = "190060839";

// ========== 状态定义 ==========
// 加载状态
const loading = ref(false);
// 验证码验证状态
const captchaVerified = ref(false);
// 验证码票据
const captchaTicket = ref('');
// 验证码随机字符串
const captchaRandStr = ref('');
// 短信验证码是否已验证
const smsVerified = ref(false);

// 验证码组件显示控制
const showLoginCaptcha = ref(false); // 控制登录验证码显示
const showSmsCaptcha = ref(false);   // 控制短信验证码显示

// 验证码实例引用
const loginCaptcha = ref<InstanceType<typeof AliyunCaptcha>>();
const smsCaptcha = ref<InstanceType<typeof AliyunCaptcha>>();

// ========== 登录相关状态 ==========
// 当前激活的标签页（password/sms）
const activeTab = ref("password");
// 手机号
const phone = ref("");
// 密码
const password = ref("");
// 短信验证码
const smsCode = ref("");
// 是否显示密码明文
const showPassword = ref(false);
// 短信倒计时
const smsCountdown = ref(0);
// 是否显示注册弹窗
const showRegisterDialog = ref(false);

// ========== 计算属性 ==========
// 手机号是否有效
const isPhoneValid = computed(() => {
  return /^1[3-9]\d{9}$/.test(phone.value);
});

// 是否可以登录（密码登录）
const canLogin = computed(() => {
  return isPhoneValid.value && password.value.length >= 6;
});

// 是否可以短信登录
const canSmsLogin = computed(() => {
  return isPhoneValid.value && smsCode.value.length === 6;
});

// 是否可以获取短信验证码
const canGetSmsCode = computed(() => {
  return isPhoneValid.value && smsCountdown.value === 0;
});

// ========== 方法定义 ==========
// 验证手机号格式（只保留数字）
const validatePhone = () => {
  phone.value = phone.value.replace(/[^\d]/g, "");
};

// 切换登录方式标签
const switchTab = (tab: string) => {
  activeTab.value = tab;
  // 切换时重置相关状态
  smsVerified.value = false;
  smsCode.value = "";
};

// 密码登录验证成功回调
const onLoginCaptchaSuccess = async ({ticket, randStr}) => {
  // 在这里调用后端验证API
  const resp = await global.$http.post('/SlideCaptchaVerify', {
    ticket,
    randStr
  });

  console.log(resp.data)

  if (resp.data.success) {
    handlePasswordLogin();
  }
}

// 密码登录逻辑
const handlePasswordLogin = async () => {
  try {
    const resp = await global.$http.post('/User/PasswordLogin', {
      phone: phone.value,
      password: password.value
    });

    console.log(resp);
    console.log(resp.data);

    if (resp.data.code === 0) {
      // 关键修复点：确保只提取纯Token（移除Bearer前缀和所有空格）
      const rawToken = resp.headers.authorization.replace(/^Bearer\s*/i, '').trim();

      localStorage.setItem('Authorization', rawToken);
      localStorage.setItem('userId', resp.data.user.id);

      console.log(localStorage);

      router.go(-1);
    } else {
      console.log(resp.data.msg)
      showToast(resp.data.msg);
    }

  } catch (error) {
    console.error('登录错误:', error);
  }
};

// 短信验证码验证成功回调
const onSmsCaptchaSuccess = (data: { ticket: string, randstr: string }) => {
  captchaTicket.value = data.ticket;
  captchaRandStr.value = data.randstr;
  captchaVerified.value = true;
  showToast("验证通过");

  // 验证通过后才允许发送短信验证码
  sendSmsCode();
};

// 验证失败统一处理
const onCaptchaFail = (error: { code: number, message: string }) => {
  loading.value = false;
  showLoginCaptcha.value = false;
  showSmsCaptcha.value = false;
  console.log(`验证失败: ${error.message}`);
};

// 发送短信验证码的实际逻辑
const sendSmsCode = async () => {
  try {
    // 开始倒计时
    smsCountdown.value = 60;
    const timer = setInterval(() => {
      smsCountdown.value--;
      if (smsCountdown.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);

    // 标记已验证通过，允许输入验证码
    smsVerified.value = true;

    // 调用API发送验证码
    showToast('验证码已发送');

    // API调用代码
    const resp = await global.$http.get('/SmsSend', {
      params: {
        mobile: phone.value
      }
    });

    console.log(resp);

  } catch (error) {
    console.error('发送短信验证码失败:', error);
    showToast('发送验证码失败');
  } finally {
    loading.value = false;
    showSmsCaptcha.value = false;
  }
};

// 触发短信验证码验证
const triggerSmsCaptcha = async () => {
  if (!canGetSmsCode.value) return;

  try {
    loading.value = true;
    // 重置验证状态
    captchaVerified.value = false;
    smsVerified.value = false;
    smsCode.value = "";

    // 显示短信验证码组件
    showSmsCaptcha.value = true;  // 显示滑动验证码组件
    await nextTick(); // 等待DOM更新

    // 调用验证码组件的显示方法
    await smsCaptcha.value?.showCaptcha();

  } catch (error) {
    loading.value = false;
    showSmsCaptcha.value = false;
    console.error('验证码显示失败:', error);
  }
};

// 触发登录验证码验证
const triggerLoginWithCaptcha = async () => {
  if (!canLogin.value) return;

  try {
    loading.value = true;

    // 每次触发都重新创建实例
    showLoginCaptcha.value = true;
    await nextTick();

    // 确保实例存在
    if (!loginCaptcha.value) {
      throw new Error('验证码实例未初始化');
    }

    // 重置验证状态
    captchaVerified.value = false;
    captchaTicket.value = '';
    captchaRandStr.value = '';

    await loginCaptcha.value.showCaptcha();
  } catch (error) {
    loading.value = false;
    showLoginCaptcha.value = false;
    console.error('验证码显示失败:', error);
    showToast('验证码初始化失败，请重试');
  }
};

// 短信验证码登录函数
const handleSmsLogin = async () => {
  try {
    const resp = await global.$http.get('/SmsVerify', {
      params: {
        mobile: phone.value,
        code: smsCode.value
      }
    });

    console.log(resp);

    if (resp.data.success) {
      const resp2 = await global.$http.post('/User/SmsLogin', {
        phone: phone.value
      });

      console.log(resp2);
      console.log(resp2.data);

      if (resp2.data.code === 0) {
        // 关键修复点：确保只提取纯Token（移除Bearer前缀和所有空格）
        const rawToken = resp2.headers.authorization.replace(/^Bearer\s*/i, '').trim();

        localStorage.setItem('Authorization', rawToken);
        localStorage.setItem('userId', resp2.data.user.id);

        console.log(localStorage);

        router.go(-1);
      } else {
        console.log(resp2.data.msg)
        showToast(resp2.data.msg);
      }
    }
  } catch (error) {
    console.error('登录错误:', error);
  }
};

const test = async () => {
  try {
    const resp = await global.$http.post('/test');

    if (resp.data === "200 token") {
      console.log("200")
    } else {
      console.log("fail")
    }
  } catch (error) {
    console.error('Token验证失败:', error.response?.status || error.message);
    if (error.response?.status === 401) {
      console.log("Token已过期或无效");
    }
  }
}
</script>

<style scoped>
/* 登录容器样式 */
.login-container {
  max-width: 100%;
  padding-top: 20px;
  box-sizing: border-box;
  /* 添加以下属性确保内容居中 */
  display: flex;
  flex-direction: column;
  /* 移除 align-items: center 或改为 stretch */
  align-items: stretch; /* 改为这个让子元素撑满 */
}

.login-form {
  /* 添加固定宽度或最大宽度 */
  width: 100%;
  max-width: 400px; /* 根据设计调整这个值 */
  margin: 0 auto; /* 水平居中 */
  padding: 20px;
  box-sizing: border-box;
}

/* Logo样式 */
.logo {
  text-align: center;
  margin: 40px 0;
}

.logo img {
  width: 200px;
  height: auto;
}

/* 登录标签页样式 */
.login-tabs {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 12px 0;
  font-size: 16px;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #ff5f16;
  font-weight: bold;
}

.tab-item.active::after {
  content: "";
  position: absolute;
  bottom: -1px;
  left: 25%;
  width: 50%;
  height: 2px;
  background-color: #ff5f16;
}

/* 表单项目样式 */
.form-item {
  position: relative;
  margin-bottom: 15px;
}

/* 输入框样式 */
.form-item input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

/* 禁用状态输入框样式 */
.form-item input:disabled {
  background-color: #f5f5f5;
  color: #999;
  cursor: not-allowed;
}

/* 登录按钮样式 */
.login-btn {
  width: 100%;
  padding: 12px;
  background-color: #ff5f16;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  margin-top: 20px;
}

/* 登录按钮禁用状态 */
.login-btn:disabled {
  background-color: #ffb08f;
  cursor: not-allowed;
}

/* 获取验证码按钮样式 */
.sms-btn {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  padding: 6px 12px;
  background-color: #ff5f16;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 12px;
}

/* 获取验证码按钮禁用状态 */
.sms-btn:disabled {
  background-color: #ffb08f;
  cursor: not-allowed;
}

/* 注册链接样式 */
.register-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
  font-size: 14px;
}

.register-link span {
  color: #ff5f16;
  text-decoration: underline;
  cursor: pointer;
}

/* 注册弹窗样式 */
.register-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}

.dialog-content {
  background-color: white;
  width: 80%;
  max-width: 300px;
  border-radius: 8px;
  padding: 20px;
  box-sizing: border-box;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  font-size: 24px;
  color: #999;
  cursor: pointer;
}

.register-btn {
  width: 100%;
  padding: 12px;
  background-color: #ff5f16;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  margin-top: 20px;
}

.register-btn:disabled {
  background-color: #ffb08f;
  cursor: not-allowed;
}
</style>